#include "lookuputils.h"

void
error_msg(const char *msg)
{
    fputs(strerror(errno), stderr);
    fputc('\n', stderr);
    fputs(msg, stderr);
    fputc('\n', stderr);
    exit(1);
}

void
info(const char *msg)
{
    fputs(msg, stdout);
    fputc('\n', stdout);
}

void
bind_and_listen(int fd, in_port_t port, int qlen)
{
    struct sockaddr_in sin;

    memset(&sin, 0, sizeof(struct sockaddr_in));

    sin.sin_family = AF_INET;
    sin.sin_addr.s_addr = INADDR_ANY;
    sin.sin_port = port;

    if (bind(fd, (struct sockaddr *) &sin, sizeof(sin)) < 0)
        error_msg("bind(): fail in socket bind");

    if (listen(fd, qlen) < 0)
        error_msg("listen(): fail to listen for socket");
}

int
create_socket(sa_family_t type)
{
    int s;

    s = socket(AF_INET, type, 0);
    if (s < 0)
        error_msg("socket(): fail to create socket");

    return s;
}

int
create_tcp_socket()
{
    return create_socket(SOCK_STREAM);
}

int create_tcp_server_socket(char *port, int qlen)
{
    int fd;

    fd = create_tcp_socket();
    bind_and_listen(fd, htons(atoi(port)), qlen);

    return fd;
}

void
connect_to_tcp_server(int fd, char *server, char *port)
{
    struct sockaddr_in srv_addr;

    memset(&srv_addr, 0, sizeof(struct sockaddr_in));

    srv_addr.sin_family = AF_INET;
    inet_aton(server, &srv_addr.sin_addr);
    srv_addr.sin_port = htons(atoi(port));

    if (connect(fd, (struct sockaddr *) &srv_addr, sizeof(srv_addr)) < 0)
        error_msg("ERROR: connecting to server");
}

